import React, { useEffect, useRef, useState } from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { View, StyleSheet, DevSettings, Modal } from 'react-native';
import { storage } from '@/utils/storage';
import { navigationRef } from '@/navigation';

// 页面组件
import { useDispatch } from 'react-redux';
import { AppDispatch } from '@/store';
import { changeLanguage, fetchAllTranslations } from '@/i18n';
import { fetchSupportedLanguages } from '@/store/slices/languageSlice';
import useCheckUpdate from '@/hooks/useCheckUpdate';
import { useNetInfo } from '@react-native-community/netinfo';
import eventBus from '@/utils/eventBus';
import Splash from '@/components/Splash';
import Signout from './modules/signout';
import ownerGlobalRoutes from './modules/ownerGlobalRoutes';
import InstallerRoutes from './modules/installerSingleRoutes';
import { useTranslation } from 'react-i18next';
import WebViewPage from '@/pages/common/WebView';
import ThemeSettingsScreen from '@/pages/common/ThemeSettings';
import {
  AdsVO,
  getAds,
  getNotification,
  NotificationVO,
} from '@/services/api/ads';
import { useAppTheme, Text, Card } from 'tsun-smart-ui';
import { useGetNaviTheme } from '@/hooks/useTheme';
import { startNetworkLogging } from 'react-native-network-logger';
import { useMMKVBoolean, useMMKVObject } from '@/hooks/useMMkv';
import ownerSingleRoutes from './modules/ownerSingleRoutes';
import { useStatusBarStyle } from '@/hooks/useStatusBarStyle';
import InstallerGlobalRoutes from './modules/installerGlobalRoutes';
import ProcessLogo from '@/assets/icon/process.svg';
import SelectAddressScreen from '@/pages/common/SelectAddressScreen';
import NativeLaunchManager from '~/specs/NativeLaunchManager';
import { APP_ENVIRONMENT_KEY } from '@/config/config';
import StringUtils from '@/utils/StringUtils';
import AppEnvironments from '@/services/AppEnvironment';
import Debugging from '@/pages/common/Debugging';
import { updateIPAddressInfo } from '@/store/slices/globalSlice';
import { createStackNavigator } from '@react-navigation/stack';
import ErrorBoundary from '@/components/ErrorBoundary';
import Notice from '@/components/Notice';
import { Platform } from 'react-native';
import { getLocales } from 'react-native-localize';
import PermissionDescription from '@/pages/common/PermissionDescription';
const isAndroid = Platform.OS === 'android';
// 创建路由栈
export const Stack = createStackNavigator<ReactNavigation.RootParamList>();
// 用户角色类型常量 - 简化为只有实际使用的角色
const USER_ROLE = {
  OWNER: 1, // 业主角色
  INSTALLER: 2, // 安装商/运营商角色
};
export const AuthContext = React.createContext<{
  setIsLoggedIn?: (value: boolean) => void;
  setUserType?: (type: 1 | 2) => void;
}>({});
// 路由配置
const AppNavigator: React.FC = () => {
  const theme = useAppTheme();
  const { t } = useTranslation();
  const dispatch = useDispatch<AppDispatch>();
  // 登录状态
  const [userType, setUserType] = useState<number | null>(null);
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const netInfo = useNetInfo();
  const [needUpdate, setNeedUpdate] = useState(false);
  const { progress, onCheckVersion, startUpdate } =
    useCheckUpdate(setNeedUpdate);
  const [globalMode = true] = useMMKVBoolean('globalMode');
  const [initialization, setInitialization] = useState(true);
  const [width, setWidth] = useState(0);
  const naviTheme = useGetNaviTheme();
  const ref = useRef<{ setIsLoad: (isLoad: boolean) => void } | null>(null);
  const [waitCheckUpdate, setWaitCheckUpdate] = useState(false);
  const [adsLoaded, setAdsLoaded] = useState(false);
  const [lngLoaded, setLngLoaded] = useState(false);
  const [ads, setAds] = useState<AdsVO>([]);
  const [noticeVisible, setNoticeVisible] = useState(false);
  const [notice, setNotice] = useState<NotificationVO[]>([]);
  const [noticeVO, setNoticeVO] = useMMKVObject<string[]>('noticeList');
  useStatusBarStyle();
  useEffect(() => {
    startNetworkLogging({
      ignoredHosts: ['clients3.google.com'],
    });
    if (__DEV__) {
      DevSettings.addMenuItem('调试工具', () => {
        navigationRef.current?.navigate('Debugging');
      });
    }
  }, []);
  // Initialize i18n
  useEffect(() => {
    const init = async () => {
      const appEnvironmentString = storage.getString(APP_ENVIRONMENT_KEY);
      const parsed = AppEnvironments.parse(appEnvironmentString);
      if (parsed) {
        AppEnvironments.current = parsed;
      } else {
        if (__DEV__) {
          AppEnvironments.current = AppEnvironments.test;
        } else {
          AppEnvironments.current = AppEnvironments.production;
        }
      }
      dispatch(updateIPAddressInfo());
      if (!__DEV__) {
        const needUpdate = await onCheckVersion();
        if (needUpdate) {
          setNeedUpdate(true);
          NativeLaunchManager.hide(theme.colors?.background?.primary);
        } else {
          setWaitCheckUpdate(true);
        }
      } else {
        setWaitCheckUpdate(true);
      }
      getNotification().then((res) => {
        if (res.data.length > 0) {
          if (noticeVO) {
            const index = noticeVO.findIndex(
              (i) => i === res.data[0].id.toString()
            );
            if (index !== -1) {
              return;
            }
          }
          setNoticeVisible(true);
          setNotice(res.data);
        }
      });
    };
    const isConnected = netInfo.isConnected;
    if (isConnected) {
      init();
    }
  }, [netInfo.isConnected, dispatch, onCheckVersion]);
  useEffect(() => {
    if (waitCheckUpdate) {
      getAds()
        .then((res) => {
          if (res.data.length > 0) {
            setAds(res.data);
          } else {
            setInitialization(false);
            setAdsLoaded(true);
          }
        })
        .catch(() => {
          setInitialization(false);
          setAdsLoaded(true);
        });
      let currentLanguage = storage.getString('language');
      if (currentLanguage) {
        changeLanguage(currentLanguage).then(() => {
          setLngLoaded(true);
        });
      } else {
        dispatch(fetchSupportedLanguages())
          .unwrap()
          .then((lngs) => {
            currentLanguage =
              lngs.find((item) =>
                item.value.includes(getLocales()[0].languageCode)
              )?.value ?? 'en-US';
            changeLanguage(currentLanguage).then(() => {
              setLngLoaded(true);
            });
          });
      }
    }
  }, [waitCheckUpdate]);
  useEffect(() => {
    if (lngLoaded && adsLoaded) {
      ref.current?.setIsLoad(true);
      fetchAllTranslations();
    }
  }, [lngLoaded, adsLoaded]);
  useEffect(() => {
    eventBus.on('LOGOUT_REQUIRED', () => {
      storage.delete('auth_token');
      storage.delete('refresh_token');
      storage.delete('user_info');
      setIsLoggedIn(false);
    });
  }, []);
  useEffect(() => {
    checkLoginStatus();
  }, []);
  const routes = isLoggedIn
    ? userType === USER_ROLE.OWNER
      ? globalMode
        ? ownerGlobalRoutes
        : ownerSingleRoutes
      : globalMode
      ? InstallerGlobalRoutes
      : InstallerRoutes
    : Signout;
  // 检查登录状态
  const checkLoginStatus = () => {
    const authToken = storage.getString('auth_token');
    const userInfoStr = storage.getString('user_info');
    if (userInfoStr) {
      const userInfo = JSON.parse(userInfoStr);
      setUserType(userInfo.userType);
    }
    setIsLoggedIn(!!authToken);
  };
  if (needUpdate) {
    return (
      <Modal
        visible={true}
        animationType="fade"
        onShow={() => {
          startUpdate?.();
        }}
      >
        <View className="flex-1 flex-center px-9" style={styles.overlay}>
          <Card
            className="w-full px-8 pt-6 pb-8"
            style={{
              borderRadius: 16,
            }}
          >
            <Text variant="cardTitle" className="text-center">
              {'A new version is being updated'}
            </Text>
            <View
              onLayout={(e) => {
                setWidth(e.nativeEvent.layout.width);
              }}
              className="w-full h-2 rounded-lg"
              style={[
                styles.progress,
                {
                  backgroundColor: theme.colors?.border?.primary,
                },
              ]}
            >
              <View
                className="h-2 rounded-lg"
                style={{
                  width: width * (progress / 100),
                  backgroundColor: theme.colors?.brand?.primary,
                }}
              ></View>
              <ProcessLogo
                style={{
                  position: 'absolute',
                  left: width * (progress / 100) - 16,
                  top: -12,
                }}
                width={32}
                height={32}
              ></ProcessLogo>
            </View>
            <Text variant="bodyMedium" className="text-center">
              {progress + '%'}
            </Text>
          </Card>
        </View>
      </Modal>
    );
  }
  if (initialization) {
    return (
      <Splash
        ads={ads}
        ref={ref}
        setAdsLoaded={setAdsLoaded}
        onPress={() => {
          setInitialization(false);
        }}
      />
    );
  }
  return (
    <>
      <AuthContext.Provider
        value={{
          setIsLoggedIn,
          setUserType,
        }}
      >
        <NavigationContainer ref={navigationRef} theme={naviTheme}>
          <Stack.Navigator
            screenOptions={{
              headerShown: true,
              headerShadowVisible: false,
              headerTitleAlign: isAndroid ? 'left' : 'center',
              // headerBackButtonDisplayMode: 'minimal',
              animation: 'slide_from_right',
              headerBackTitle: t('sys.app.back', { defaultValue: '返回' }),
              headerStyle: {
                backgroundColor: naviTheme.colors.background,
              },
              // gestureResponseDistance: 1000,
            }}
            screenLayout={(props) => (
              <ErrorBoundary>{props.children}</ErrorBoundary>
            )}
          >
            {routes.map((route) => (
              <Stack.Screen
                key={route.name}
                name={route.name}
                component={route.component}
                options={
                  typeof route.options === 'function'
                    ? route.options(t, naviTheme)
                    : route.options
                }
              />
            ))}
            <Stack.Group navigationKey={userType?.toString()}>
              <Stack.Screen
                name="CountryPicker"
                options={{
                  headerTitle: t(
                    'userSetting.basicInfo.form.label.countryRegion',
                    {
                      defaultValue: '国家/地区',
                    }
                  ),
                }}
                component={require('@/pages/common/CountryPicker').default}
              />

              <Stack.Screen
                name="LanguageSettings"
                options={{
                  headerTitle: t('user.title1'),
                }}
                component={require('@/pages/common/LanguageSettings').default}
              />

              <Stack.Screen name="WebView" component={WebViewPage} />

              <Stack.Screen
                name="ThemeSettings"
                component={ThemeSettingsScreen}
                options={{
                  title: t('layout.skin'),
                }}
              />
              <Stack.Screen
                options={{ headerShown: true, title: '调试工具' }}
                name="Debugging"
                component={Debugging}
              />
              <Stack.Screen
                options={{
                  headerShown: true,
                  title: t('sys.app.select.address', {
                    defaultValue: '选择地址',
                  }),
                }}
                name="SelectAddress"
                component={SelectAddressScreen}
              />
              <Stack.Screen
                name="PermissionDescription"
                component={PermissionDescription}
                options={{
                  presentation: 'transparentModal',
                  headerShown: false,
                  animation: 'none',
                }}
              />
            </Stack.Group>
          </Stack.Navigator>
        </NavigationContainer>
      </AuthContext.Provider>
      <Notice
        visible={noticeVisible}
        notice={notice}
        onPress={() => {
          setNoticeVisible(false);
          setNoticeVO((pre) => {
            return [...(pre ?? []), notice[0].id.toString()];
          });
        }}
      />
    </>
  );
};

const styles = StyleSheet.create({
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  progress: {
    marginTop: 40,
    position: 'relative',
    marginBottom: 20,
  },
  overlay: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'rgba(0, 0, 0, 0.3)',
  },
});

export default AppNavigator;
